import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_boost/flutter_boost.dart';
import 'package:flutter_module/common/base/base_page.dart';
import 'package:flutter_module/common/utils/object_to_any.dart';
import 'package:flutter_module/common/utils/toast_utils.dart';
import 'package:flutter_module/common/widget/CustomDialog.dart';
import 'package:flutter_module/core/flutter_bridge.dart';
import 'package:flutter_module/model/native_image_options.dart';
import 'package:flutter_module/model/service_provider_audit_state.dart';
import 'package:flutter_module/model/service_provider_detail_model.dart';
import 'package:flutter_module/page/base/arrow_left_right_view.dart';
import 'package:flutter_module/page/cooperation/widgets/cooperation_intro_item.dart';
import 'package:flutter_module/page/cooperation/widgets/cooperation_title_content_container.dart';
import 'package:flutter_module/page/cooperation/widgets/service_obj_container.dart';
import 'package:flutter_module/api/service_provider_edit_request.dart';
import 'package:flutter_module/page/service_provider_edit/widgets/service_provider_banner.dart';
import 'package:flutter_module/page/service_provider_edit/widgets/service_provider_edit_cases.dart';
import 'package:flutter_module/page/service_provider_edit/widgets/service_provider_edit_container.dart';
import 'package:flutter_module/page/service_provider_edit/widgets/service_provider_edit_footer.dart';
import 'package:flutter_module/page/service_provider_edit/widgets/service_provider_edit_logo.dart';
import 'package:flutter_module/routers.dart';
import 'package:flutter_module/style/colors.dart';

/// 合作服务商编辑页
class ServiceProviderEditPage extends BaseStateFulWidget {
  @override
  BaseState<StatefulWidget> buildState() {
    return _ServiceProviderEditPageState();
  }
}

class _ServiceProviderEditPageState extends BaseState<ServiceProviderEditPage>
    with BasePage<ServiceProviderEditPage> {
  ServiceProviderDetailModel? _editData;

  final int _childLength = 7;
  final _logoKey = GlobalKey<ServiceProviderEditLogoState>();
  final _contentStyle = TextStyle(
    color: ThemeColors.text888,
    fontSize: 11.0,
    fontWeight: FontWeight.w500,
  );

  /// 案例列表刷新
  StateSetter? caseRefresh;

  ServiceProviderDetailModel get _data {
    assert(_editData != null, '合作服务商数据未加载成功前不能调用_data，请检查代码是否正确调用');
    return _editData!;
  }

  @override
  Widget createView(BuildContext context) {
    print('_ServiceProviderEditPageState.createView');
    return SafeArea(
      child: Column(
        children: [
          Expanded(
            child: Scrollbar(
              child: CustomScrollView(
                slivers: [
                  SliverList(
                    delegate: SliverChildBuilderDelegate(
                      (context, index) {
                        if (index.isOdd) {
                          return SizedBox(
                            height: 10,
                          );
                        }
                        final _index = index ~/ 2;
                        switch (_index) {
                          case 0:
                            return _bannerWidget;
                          case 1:
                            return _logoReplaceWidget;
                          case 2:
                            return _preferentialPolicyWidget;
                          case 3:
                            return _profileWidget;
                          case 4:
                            return _serviceScopeWidget;
                          case 5:
                            return _serviceObjectsWidget;
                          default:
                            return ServiceProviderItemHeader(
                              title: '案例展示',
                              right: ArrowLeftRightView(
                                title: '新增案例',
                              ),
                              onTap: () async {
                                final handler = caseRefresh ?? setState;
                                final result =
                                    await BoostNavigator.instance.push(
                                  CooperationRouters.EDIT_CASE_SHOW,
                                );
                                print(result);
                                final newItem =
                                    ServiceProviderCaseModel.fromMap(
                                        object2map(result));
                                handler(() => _data.caseList.add(newItem));
                              },
                            );
                        }
                      },
                      childCount: (_childLength * 2) - 1,
                    ),
                  ),
                  _caseListWidget,
                ],
                physics: BouncingScrollPhysics(
                    parent: AlwaysScrollableScrollPhysics()),
              ),
            ),
          ),
          ServiceProviderEditFooter(
            state: _data.editStatus,
            reasonRejection: _data.editRefuseReason,
            onAction: (state) {
              if (state == ServiceProviderAuditState.prepareSubmission) {
                _submitChangeInfo();
              }
            },
          ),
        ],
      ),
    );
  }

  /// 服务对象
  Widget get _serviceObjectsWidget {
    return StatefulBuilder(
      builder: (context, setState) {
        return ServiceProviderEditContainer(
          child: CooperationTitleContainer(
            title: "服务对象",
            children: [
              ServiceObjContainer(
                datas: _data.targetCodeName,
                contentTextStyle: _contentStyle.copyWith(height: 1.7),
              )
            ],
          ),
          onEdit: () async {
            // 编辑完成，通过setState更新
            final result = await BoostNavigator.instance.push(
              CooperationRouters.EDIT_SERVICE_OBJECT,
              arguments: {
                'targetCodeName': _data.targetCodeName.toList(),
                'targetCode': _data.targetCode.toList()
              },
            );
            final map = object2map(result);
            if (map.containsKey('targetCodeName')) {
              _data.targetCodeName = object2list<String>(map['targetCodeName']);
            }

            if (map.containsKey('targetCode')) {
              _data.targetCode = object2list<String>(map['targetCode']);
            }
            setState(() {});
          },
        );
      },
    );
  }

  /// 服务范围
  Widget get _serviceScopeWidget {
    return StatefulBuilder(
      builder: (context, setState) {
        return ServiceProviderEditContainer(
          child: CooperationTitleContainer(
            title: '服务范围',
            children: [
              ..._data.serviceScope.map(
                (e) => Text(
                  e,
                  style: _contentStyle,
                ),
              )
            ],
          ),
          onEdit: () async {
            // 编辑完成，通过setState更新
            final result = await BoostNavigator.instance.push(
              CooperationRouters.EDIT_SERVICE_SCOPE,
              arguments: {'serviceScope': _data.serviceScope.toList()},
            );

            final map = object2map(result);
            if (map.containsKey('serviceScope')) {
              _data.serviceScope = object2list<String>(map['serviceScope']);
              setState(() {});
            }
          },
        );
      },
    );
  }

  /// logo替换
  Widget get _logoReplaceWidget {
    return ServiceProviderEditLogo(
      key: _logoKey,
      logoUrl: _data.companyLogoUrl,
      onTap: () async {
        final url =
            await FlutterPlatformBridge.getInstance().selectAndUploadFromPhotos(
          imageOptions: const NativeImageOptions(
            directory: 'service/provider',
          ),
        );
        if (url.isNotEmpty) {
          _data.companyLogoUrl = url;
          _logoKey.currentState?.logoUrl = url;
        }
      },
    );
  }

  /// 优惠政策
  Widget get _preferentialPolicyWidget {
    return StatefulBuilder(
      builder: (context, setState) {
        return ServiceProviderEditContainer(
          child: CooperationTitleContainer(
            title: '优惠政策',
            children: [
              if (_data.preferential.isNotEmpty)
                Text(
                  _data.preferential,
                  style: _contentStyle,
                )
            ],
          ),
          onEdit: () async {
            // 编辑完成，通过setState更新
            final result = await BoostNavigator.instance.push(
              CooperationRouters.EDIT_FAVOURED_POLICY,
              arguments: {'preferential': _data.preferential},
            );

            final map = object2map(result);
            if (map.containsKey('preferential')) {
              _data.preferential = object2string(map['preferential']);
              setState(() {});
            }
          },
        );
      },
    );
  }

  /// 轮播图
  Widget get _bannerWidget {
    return StatefulBuilder(
      builder: (context, setState) {
        return ServiceProviderBanner(
          bannerImgUrls: _data.kvImage,
          fit: BoxFit.cover,
          onEdit: () async {
            // 编辑完成，通过setState更新
            final result = await BoostNavigator.instance.push(
              CooperationRouters.EDIT_BANNER, //required
              arguments: {"imgList": _data.kvImage.toList()}, //optional
            );

            final list = object2list<String>(result);
            _data.kvImage = list;
            setState(() {});
          },
        );
      },
    );
  }

  /// 简介
  Widget get _profileWidget {
    return StatefulBuilder(
      builder: (context, setState) {
        return ServiceProviderEditContainer(
          child: CooperationIntroItem(
            videoCover: _data.videoImage,
            videoUrl: _data.videoUrl,
            content: _data.companyProfile,
            titleStyle: TextStyle(
              color: ThemeColors.text333,
              fontSize: 14.0,
              fontWeight: FontWeight.bold,
            ),
            contentStyle: _contentStyle,
          ),
          onEdit: () async {
            final result = await BoostNavigator.instance.push(
              CooperationRouters.profileEdit,
              arguments: _data.toMap(),
            );
            var isNeedUpdate = false;
            final currentResult = object2map(result);
            if (currentResult.containsKey('companyProfile')) {
              _data.companyProfile =
                  object2string(currentResult['companyProfile']);
              isNeedUpdate = true;
            }

            if (currentResult.containsKey('videoImage')) {
              _data.videoImage = object2string(currentResult['videoImage']);
              isNeedUpdate = true;
            }
            if (currentResult.containsKey('videoUrl')) {
              _data.videoUrl = object2string(currentResult['videoUrl']);
              isNeedUpdate = true;
            }
            if (isNeedUpdate) {
              setState(() {});
            }
          },
        );
      },
    );
  }

  /// 案例列表内容
  Widget _caseListContentWidget(StateSetter setState) {
    return Container(
      padding: EdgeInsets.only(left: 16.0, right: 16.0, bottom: 28.0),
      color: Colors.white,
      child: GridView.builder(
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          mainAxisSpacing: 10.0,
          crossAxisSpacing: 10.0,
          crossAxisCount: 2,
          childAspectRatio: 167.0 / 147.0,
        ),
        itemBuilder: (context, index) {
          final item = _data.caseList[index];
          return ServiceProviderCaseItem(
            title: item.title,
            imgUrl: item.images.first,
            onEdit: () async {
              final result = await BoostNavigator.instance.push(
                CooperationRouters.EDIT_CASE_SHOW,
                arguments: item.toMap(returnOnlyKeyFields: true),
              );
              final newItem =
                  ServiceProviderCaseModel.fromMap(object2map(result));
              setState(() => _data.caseList[index] = newItem);
            },
            onDelete: () {
              showDialog(
                context: context,
                barrierDismissible: false,
                builder: (_) {
                  return CustomDialog(
                    content: '确定要删除该案例？',
                    cancelContent: "取消",
                    confirmContent: "删除",
                    confirmCallback: () {
                      setState(() => _data.caseList.removeAt(index));
                    },
                  );
                },
              );
            },
            onTouch: () {
              BoostNavigator.instance.push(
                CooperationRouters.CASE_DETAILS,
                arguments: item.toMap(),
              );
            },
          );
        },
        itemCount: _data.caseList.length,
      ),
    );
  }

  /// 案例列表
  Widget get _caseListWidget {
    return StatefulBuilder(
      builder: (context, setState) {
        caseRefresh = setState;
        return SliverToBoxAdapter(
            child: _data.caseList.isNotEmpty
                ? _caseListContentWidget(setState)
                : SizedBox.shrink());
      },
    );
  }

  /// 提交更改的信息
  void _submitChangeInfo() {
    var params = Map<String, dynamic>();
    params['id'] = _data.id;
    params['companyProfile'] = _data.companyProfile;
    params['kvImage'] = _data.kvImage.join(',');
    params['preferential'] = _data.preferential;
    params['videoUrl'] = _data.videoUrl;
    params['videoImage'] = _data.videoImage;
    params['serviceScope'] = _data.serviceScope.join(',');
    params['companyLogoUrl'] = _data.companyLogoUrl;
    params['caseParams'] =
        _data.caseList.map((e) => e.toMap(returnOnlyKeyFields: true)).toList();
    params['targetCode'] = _data.targetCode.join(',');
    print('将要提交的参数 $params');
    final request = ServiceProviderEditRequest();
    request.bodyParams.addAll(params);
    request.request(
      this,
      (result) {
        ToastUtils().showText('提交成功');
        super.onBack();
      },
    );
  }

  void _loadData() async {
    var request = ServiceProviderDetailRequest();
    try {
      final result = await request.fire(this);
      _editData = ServiceProviderDetailModel.fromMap(result);
      setState(() => isLoading = false);
    } catch (e) {
      setState(() => isEmpty = true);
    }
  }

  @override
  void initState() {
    print('_ServiceProviderEditPageState.initState');
    if (kDebugMode) {
      print('当前debug模式');
    } else if (kReleaseMode) {
      print('release模式');
    }
    isLoading = true;
    _loadData();
    super.initState();
  }

  @override
  void dispose() {
    print('_ServiceProviderEditPageState.dispose');
    super.dispose();
  }

  @override
  void didUpdateWidget(oldWidget) {
    print('_ServiceProviderEditPageState.didUpdateWidget');
    super.didUpdateWidget(oldWidget);
  }

  @override
  void didChangeDependencies() {
    print('_ServiceProviderEditPageState.didChangeDependencies');
    super.didChangeDependencies();
  }

  @override
  void deactivate() {
    print('_ServiceProviderEditPageState.deactivate');
    super.deactivate();
  }

  @override
  void reassemble() {
    print('_ServiceProviderEditPageState.reassemble');
    super.reassemble();
  }

  @override
  String get appBarTitle => '我的主页';
}
